<script setup lang="ts">
import type { EquipmentDefinition } from '@/types'

import { Delete, Top, Bottom } from '@element-plus/icons-vue'
import { EQUIPMENT_COMPONENT_TYPE, EQUIPMENT_INPUT_DATA_TYPE } from '@/enum'

import ErrorMessage from './error-message.vue'

defineOptions({
  name: 'TextComponent',
})

defineProps<{
  disabled?: boolean
  isPoint?: boolean
  showTopButton?: boolean
  showBottomButton?: boolean
  disableTopButton?: boolean
  disableBottomButton?: boolean
}>()

const emit = defineEmits<{
  (e: 'remove', id: number | string): void
  (e: 'move', id: number | string, direction: 'top' | 'bottom'): void
}>()

const info = defineModel<EquipmentDefinition>({ required: true })
const error = ref(false)

function isEmpty(val: any) {
  return val === undefined || val === null || val === ''
}
function validate() {
  let ret = true
  if (isEmpty(info.value.name)) {
    ret = false
  }
  if (info.value.type === EQUIPMENT_COMPONENT_TYPE.SELECT && isEmpty(info.value.urlAddr)) {
    ret = false
  }
  error.value = !ret
  return ret
}

defineExpose({
  validate,
})

onMounted(() => {
  if (!info.value.dataType) {
    info.value.dataType = EQUIPMENT_INPUT_DATA_TYPE.TEXT
  }
})
</script>

<template>
  <div class="fs-14 flex items-center gap-3 p-3">
    <ElInput v-model="info.name" class="w-140" placeholder="请输入..." :disabled="disabled" clearable />
    <span class="flex-shrink-0 opacity-50">类型:</span>
    <span class="flex-shrink-0">文本</span>
    <span class="flex-shrink-0 opacity-50">数据类型:</span>
    <ElSelect v-model="info.dataType" class="no-bg !w-20" :disabled="disabled || isPoint" :clearable="false">
      <ElOption label="文本" :value="EQUIPMENT_INPUT_DATA_TYPE.TEXT" />
      <ElOption label="点位" :value="EQUIPMENT_INPUT_DATA_TYPE.POINT" />
    </ElSelect>
    <ElCheckbox v-model="info.required" label="必填" :disabled="disabled" :true-value="1" :false-value="0" />
    <ElButton v-if="showTopButton" class="ml-4" :disabled="disableTopButton" :icon="Top" circle plain title="上移" type="success" @click="emit('move', info._uuid, 'top')" />
    <ElButton v-if="showBottomButton" class="!ml-0" :disabled="disableBottomButton" :icon="Bottom" circle plain title="下移" type="success" @click="emit('move', info._uuid, 'bottom')" />
    <ElButton v-if="!disabled && info.fixed !== 1" class="!ml-0" circle plain :icon="Delete" title="删除" type="danger" @click="emit('remove', info._uuid)" />
    <ErrorMessage :error="error" />
  </div>
</template>

<style scoped>
.no-bg :deep(.el-select__wrapper) {
  background-color: transparent !important;
  box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
}
</style>
